import React, { useState, useRef, useEffect } from 'react';
import styles from './index.module.scss';
import { NavBar, Form, Input, List, Button, Toast } from 'antd-mobile';
import { useHistory, useLocation } from 'react-router-dom';
import { loginType } from '@/types/data';
import { useDispatch } from 'react-redux';
import { getCode, login } from '@/store/actions/login';
import { FormInstance } from 'antd-mobile/es/components/form';
import { InputRef } from 'antd-mobile/es/components/input';
export default function Login() {
  const history = useHistory();
  const dispatch = useDispatch();
  // 设置状态,用来控制获取验证码的显示和影藏
  const [time, setTime] = useState(0);
  const formRef = useRef<FormInstance>(null);
  const inputRef = useRef<InputRef>(null);
  const timerRef = useRef(-1);
  const location = useLocation<{ from: string }>();
  // console.log(location.state?.from);
  // const pathname = location.state?.from;
  // 获取表单数据
  const onFinish = async (value: loginType) => {
    //发起请求
    await dispatch(login(value));
    //消息提示
    Toast.show({
      content: '登录成功',
      duration: 200,
      afterClose: () => {
        //成功后页面跳转=====>判断location.pathname
        const { from } = location.state || { from: '/home' };
        history.replace(from);
      },
    });
  };
  //获取验证码
  const onClick = async () => {
    if (time > 0) return;
    //1.先判断是否有手机号,并且是否填写正确,正确就发送请求,其余的就让输入框聚集
    //获取Form表单的方法
    const value = formRef.current?.getFieldValue('mobile');
    const msg = formRef.current?.getFieldError('mobile');
    if (!value || msg?.length !== 0) {
      // 输入框聚焦
      inputRef.current?.focus();
      return;
    }
    // console.log('发请求获取验证码');
    await dispatch(getCode(value));
    // 获取验证码请求成功后,就开始时
    setTime(60);
    timerRef.current = window.setInterval(() => {
      setTime((time) => time - 1);
    }, 1000);
  };
  useEffect(() => {
    if (time === 0) {
      //清除定时器
      window.clearInterval(timerRef.current);
    }
  }, [time]);
  //如果定时器还没有运行完,就跳转页面了,就需要另外销毁组件了
  useEffect(() => {
    return () => {
      window.clearInterval(timerRef.current);
    };
  }, []);
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>
      <div className="login-form">
        <h2 className="title">短信登录</h2>
        <Form
          validateTrigger={['onChange', 'onBlur']}
          autoComplete="off"
          onFinish={onFinish}
          initialValues={{ mobile: '13811111111', code: '246810' }}
          ref={formRef}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
            ]}
          >
            <Input
              placeholder="请输入手机号"
              maxLength={11}
              ref={inputRef}
            ></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={onClick}>
                {time === 0 ? '发送验证码' : `${time}秒后在获取`}
              </span>
            }
          >
            <Form.Item
              className="login-item"
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '请输入6位验证码' },
              ]}
            >
              <Input placeholder="请输入验证码" maxLength={6}></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              color="primary"
              block
              className="login-submit"
              type="submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
